﻿// <copyright file="LearnSensor.cs" company="Hallvard Korsgaard">
//  Microsoft Public License (Ms-PL). See license details here: http://enoceannet.codeplex.com/license
// </copyright>
// <author>Hallvard Korsgaard</author>

namespace StcEthernet.Management
{
  using System;
  using EnOcean;

  /// <summary>
  /// Manual learn-in of an EnOcean transmitter.
  /// </summary>
  [Serializable]
  public class LearnSensor : ManagementTelegram
  {
    /// <summary>
    /// Variable for the Id property.
    /// </summary>
    private long id;

    /// <summary>
    /// Initializes a new instance of the LearnSensor class.
    /// </summary>
    public LearnSensor()
    {
    }

    /// <summary>
    /// Initializes a new instance of the LearnSensor class.
    /// </summary>
    /// <param name="org">The org byte value.</param>
    /// <param name="channel">The transiever channel to program.</param>
    /// <param name="id">The sensor id to learn.</param>
    public LearnSensor(Org org, byte channel, long id)
    {
      this.Org = org;
      this.Channel = channel;
      this.Id = id;
    }

    /// <summary>
    /// Gets or sets the org byte.
    /// </summary>
    public Org Org
    {
      get;
      set;
    }

    /// <summary>
    /// Gets or sets the channel to use for this transmitter.
    /// </summary>
    public byte Channel
    {
      get;
      set;
    }

    /// <summary>
    /// Gets or sets the 32 bit transmitter ID. The ID must be in the range 0 to 0xffffffff inclusive.
    /// </summary>
    public long Id
    {
      get
      {
        return this.id;
      }

      set
      {
        if (value >= 0x0 && value <= 0xffffffff)
        {
          this.id = value;
        }
        else
        {
          throw new ArgumentOutOfRangeException("Id", "must be a 32 bit value in the range 0x0 to 0xffffffff inclusive");
        }
      }
    }

    /// <summary>
    /// Creates the byte format of the message.
    /// </summary>
    /// <param name="message">A byte array of length 10 to hold the message contents.</param>
    protected internal override void CreateMessage(byte[] message)
    {
      byte[] i;
      
      base.CreateMessage(message);

      i = BitConverter.GetBytes(this.Id);

      message[2] = 0x92;
      message[3] = this.Channel;
      message[4] = (byte)Org;
      message[5] = i[3];
      message[6] = i[2];
      message[7] = i[1];
      message[8] = i[0];
      message[9] = 0x00;
    }
  }
}
